//
//  KLBrunchDetailViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 17/2/22.
//  Copyright © 2017年 陈宾鹏. All rights reserved.
//

#import "KLBrunchDetailViewController.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "KLHttpAPI.h"
#import "Masonry.h"
#import "JRToast.h"
#import "HemaFunction.h"

@interface KLBrunchDetailViewController () <UITableViewDelegate,UITableViewDataSource>
{
    BOOL enableEdit;
}
@property (weak, nonatomic) IBOutlet UIView *headVIew;
@property (weak, nonatomic) IBOutlet UIView *boardView;
@property (weak, nonatomic) IBOutlet UILabel *groupName;
@property (weak, nonatomic) IBOutlet UILabel *lockNum;
@property (weak, nonatomic) IBOutlet UILabel *editName;
@property (weak, nonatomic) IBOutlet UILabel *detailNum;
@property (weak, nonatomic) IBOutlet UIButton *editNameBtn;
@property (nonatomic,strong) UITableView *lockListTV;
@property (nonatomic,strong) UIButton *editBtn;

@property (nonatomic,strong) NSMutableArray *lock_list_arr;
@end

@implementation KLBrunchDetailViewController
-(UITableView *)lockListTV{
    if(!_lockListTV){
        _lockListTV = [[UITableView alloc]init];
        _lockListTV.delegate = self;
        _lockListTV.dataSource = self;
        _lockListTV.bounces = NO;
        _lockListTV.separatorInset = UIEdgeInsetsMake(0, -40, 0, 0);
        _lockListTV.tableFooterView = [[UIView alloc]init];
        _lockListTV.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    }
    return _lockListTV;
}

-(NSMutableArray *)lock_list_arr{
    if(!_lock_list_arr){
        _lock_list_arr = [NSMutableArray array];
    }
    return _lock_list_arr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"钥匙串详情";
    self.view.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    [self mainUISet];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 设置主界面
-(void)mainUISet{
    //设置钥匙串图片
    self.boardView.layer.masksToBounds = YES;
    self.boardView.layer.cornerRadius = 8;
    self.boardView.layer.borderWidth = 0.6;
    self.boardView.layer.borderColor = [UIColor blackColor].CGColor;
    //设置文字lable
    self.groupName.textColor = RGB_UI_COLOR(115, 115, 115);
    self.groupName.font = [UIFont systemFontOfSize:16 weight:0.7];
    self.lockNum.textColor = RGB_UI_COLOR(115, 115, 115);
    self.lockNum.font = [UIFont systemFontOfSize:16 weight:0.7];
    //设置显示名字的label和显示数量的label
    self.editName.text = [self.groupDic objectForKey:@"group_name"];
    self.editName.font = [UIFont systemFontOfSize:16];
    self.editName.textColor = RGB_UI_COLOR(255, 105, 180);
    self.detailNum.text = [NSString stringWithFormat:@"%@把",[self.groupDic objectForKey:@"count"]];
    self.detailNum.font = [UIFont systemFontOfSize:16];
    self.detailNum.textColor = RGB_UI_COLOR(255, 105, 180);
    //设置tableview
    [self.view addSubview:self.lockListTV];
    [self.lockListTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.headVIew).with.offset(150);
        make.bottom.mas_equalTo(-70);
    }];
    //设置保存按钮
    NSString *type = [self.groupDic objectForKey:@"type"];
    if(type.integerValue == 1){
        self.editBtn = [[UIButton alloc]init];
        self.editBtn.backgroundColor = RGB_UI_COLOR(8, 128, 181);
        [self.editBtn setTitle:@"编辑钥匙串" forState:UIControlStateNormal];
        self.editBtn.titleLabel.font = [UIFont systemFontOfSize:19 weight:0.7];
        enableEdit = NO;
        self.editBtn.layer.masksToBounds = YES;
        self.editBtn.layer.cornerRadius = 5;
        [self.editBtn addTarget:self action:@selector(doEdit:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.editBtn];
        [self.editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.right.mas_equalTo(-15);
            make.height.mas_equalTo(44);
            make.bottom.mas_equalTo(-13);
        }];
    }
    //获取钥匙串内的数据
    [self getCurrentBrunch];
}-(void)doEdit:(id)sender{
    if(enableEdit == NO){
        [self.editBtn setTitle:@"保存" forState:UIControlStateNormal];
        [self editBrunch];
    }else{
        [self.editBtn setTitle:@"编辑钥匙串" forState:UIControlStateNormal];
        //将新建的钥匙串保存给服务器
        [self saveBrunch];
    }
    enableEdit = !enableEdit;
    [self.lockListTV setEditing:enableEdit];
    

}

#pragma mark - UITableViwDelegate和dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.lock_list_arr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LockListTV"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"LockListTV"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
    
    UIImageView *iv = [[UIImageView alloc]init];
    iv.image = [UIImage imageNamed:@"lockround"];
    [cell.contentView addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell);
        make.size.mas_equalTo(CGSizeMake(29, 38));
        make.left.equalTo(cell.contentView).with.offset(10);
    }];
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    nameLabel.text = [NSString stringWithFormat:@"别名：%@",[lockDic objectForKey:@"name"]];
    nameLabel.font = [UIFont systemFontOfSize:16];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell.contentView).with.offset(3);
        make.right.equalTo(cell.contentView).with.offset(-10);
        make.height.mas_equalTo(30);
        make.left.equalTo(iv).with.offset(40);
    }];
    
    UILabel *addressLabel = [[UILabel alloc]init];
    addressLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    addressLabel.text = [NSString stringWithFormat:@"地址：%@",[lockDic objectForKey:@"address"]];
    addressLabel.font = [UIFont systemFontOfSize:14];
    addressLabel.textColor = RGB_UI_COLOR(120, 120, 120);
    addressLabel.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:addressLabel];
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(cell.contentView).with.offset(-3);
        make.right.equalTo(cell.contentView).with.offset(-10);
        make.height.mas_equalTo(30);
        make.left.equalTo(iv).with.offset(40);
    }];
    if(enableEdit){
        NSString *type = [lockDic objectForKey:@"type"];
        if(type.integerValue == 1){
            [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        }else if (type.integerValue == 0){
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
        }
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
//    NSString *lock_id = [lockDic objectForKey:@"id"];
//    NSDictionary *dic = [NSDictionary dictionaryWithObject:lock_id forKey:@"lock_id"];
//    [self.selectLock addObject:dic];
//    self.numLabel.text = [NSString stringWithFormat:@"%zd把",self.selectLock.count];
//    NSLog(@"%@",self.selectLock);
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
//    NSString *lock_id = [lockDic objectForKey:@"id"];
//    NSDictionary *dic = [NSDictionary dictionaryWithObject:lock_id forKey:@"lock_id"];
//    [self.selectLock removeObject:dic];
//    self.numLabel.text = [NSString stringWithFormat:@"%zd把",self.selectLock.count];
//    NSLog(@"%@",self.selectLock);
 
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15.f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

#pragma mark -编辑组名按钮
- (IBAction)editNameBtn:(UIButton *)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"原名称为：%@",[self.groupDic objectForKey:@"group_name"]] preferredStyle:UIAlertControllerStyleAlert];
    //定义第一个输入框
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入新的名字";
    }];
    //增加确定按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //获取第1个输入框
        UITextField *userNameTextField = alertController.textFields.firstObject;
        NSLog(@"修改后的名字:%@",userNameTextField.text);
        if([HemaFunction xfunc_check_strEmpty:userNameTextField.text]){
            [JRToast showWithText:@"请输入新的组名"];
            return ;
        }
        [KLHelp showHUDAddedTo:self.view animated:YES];
        [KLHttpAPI editGroupBrunchNameWithGroup_id:[self.groupDic objectForKey:@"id"] type:[self.groupDic objectForKey:@"type"] group_name:userNameTextField.text completionHandler:^(MKNetworkOperation *operation) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSDictionary *dic = operation.responseJSON;
            NSString *isSuccess = [dic objectForKey:@"success"];
            if(isSuccess.integerValue == 1){
                self.editName.text = userNameTextField.text;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"editBrunchNameSuccess" object:nil];
            }
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        } errorHandler:^(NSString *error) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [JRToast showWithText:error];
        }];
    }]];
    //增加取消按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:true completion:nil];
}

#pragma mark -刷新钥匙串里的数据
-(void)getCurrentBrunch{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestAllLocksOfBrunchWithID:[self.groupDic objectForKey:@"id"] type:[self.groupDic objectForKey:@"type"] completionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"获取一个钥匙串里的所有锁数据：%@",operation.responseString);
        NSDictionary *dic = operation.responseJSON;
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            NSArray *arr = [dic objectForKey:@"infor"];
            self.lock_list_arr = [arr copy];
            [self.lockListTV reloadData];
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:error];
    }];
}

#pragma mark - 编辑钥匙串里的数据
-(void)editBrunch{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestEditCurrentBrunchWithGroup_id:[self.groupDic objectForKey:@"group_id"] completionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"编辑钥匙拿到的数据:%@",operation.responseString);
        NSDictionary *dic = operation.responseJSON;
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            NSArray *infor = [dic objectForKey:@"infor"];
            self.lock_list_arr = [infor copy];
            [self.lockListTV reloadData];
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:error];
    }];
}

#pragma mark - 保存钥匙串里的数据
-(void)saveBrunch{
    NSMutableArray *selectLocks = [NSMutableArray array];
    NSArray *indexArr = [self.lockListTV indexPathsForSelectedRows];
    for (NSIndexPath *index in indexArr) {
        NSDictionary *lockDic = self.lock_list_arr[index.row];
        NSString *lock_id = [lockDic objectForKey:@"id"];
        NSDictionary *dic = [NSDictionary dictionaryWithObject:lock_id forKey:@"lock_id"];
        [selectLocks addObject:dic];
    }
    NSLog(@"选中的锁:%@",selectLocks);
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestSaveCurrentBrunchWithGroup_id:[self.groupDic objectForKey:@"group_id"] lockList:selectLocks completionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"修改组返回数据:%@",operation.responseString);
        NSDictionary *result = operation.responseJSON;
        NSString *isSuccess = [result objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            [self getCurrentBrunch];
        }else{
            [JRToast showWithText:[result objectForKey:@"msg"]];
        }
        [KLHelp hideAllHUDsForView:self.view animated:YES];
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:error];
    }];
}
@end
